# -*-coding:utf-8-*-

import json
import time
import sys
import urllib
import unittest
from tornado.httpclient import HTTPClient, HTTPRequest
from tests import configs
from apis.http import *
from utils.sign import sign_arguments
import logging
from tornado.options import options
from tests.apis import *
import settings


options.parse_command_line()

_api_set_mapping = {
    'users': users.Users,
    'devices': devices.Devices,
    'entries': entries.Entries,
    'roles': roles.Roles,
    'apps': apps.Apps,
    'orders': orders.Orders,
    'products': products.Products,
    'transfers': transfers.Transfers,
}


class BaseTestCase(unittest.TestCase):
    def __init__(self, methodName='runTest'):
        super(BaseTestCase, self).__init__(methodName)
        self.user = None
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.ERROR)
        # self.logger.setLevel(logging.WARNING)

    def print_obj(self, obj, desc=None):
        if desc is not None:
            print '\n-> ', desc, ' <-'
        print self.format_obj(obj)

    def format_obj(self, obj):
        return json.dumps(obj, indent=4, ensure_ascii=False).encode('utf-8')

    def get_api_set(self, api_set_name, *args, **kwargs):
        kwargs.update(base_test_case_obj=self)
        return _api_set_mapping[api_set_name](*args, **kwargs)

    def get_root_user(self):
        root_access_token = 'fq9SgE30yDowt6pMfCemD0NBN0UwQkUzMDJERjIyRjlDRjQzMTVCRENGNjZCNjJERHF1Zun7EHWxFmZ82q-uabdIYjDYMAlq-hbqVbs-z-dQuldlH5lVZ1TxswIDSdf_uh0s7RuRcRkGYhxT'
        return self.get_api_set('users', access_token=root_access_token, uid=settings.root_user_id)

    def login_then_update_access_token(self, password):
        response = self.login()
        self.assertEqual(response.code, 200, response.reason)
        response = json.loads(response.body)
        self.assertTrue(response['result'], response['error_message'])

        self.access_token = response['data']['access_token']
        self.user_id = response['data']['user_id']

    def build_common_arguments(self):
        arguments = {}
        arguments['appkey'] = configs.TEST_APP_KEY  # '93F9C5720748E3F37F591D295EF61A8A'
        arguments['timestamp'] = int(time.time())
        return arguments

    def register(self, username=configs.USERNAME, password=configs.PASSWORD, spreader=None):
        user = self.get_api_set('users')
        specifics = {'spreader': spreader}
        user.register(username=username, password=password, specifics=specifics)

    def unregister(self, username=configs.USERNAME):
        user = self.get_api_set('users')
        user.unregister(username==username)

    def login(self, username=configs.USERNAME, password=configs.PASSWORD):
        self.user = self.get_api_set('users')
        self.user.login(username=configs.USERNAME, password=configs.PASSWORD)

    def assert_response_success(self, response):
        self.assertEqual(response.code, 200, response.reason)
        response = json.loads(response.body)
        self.assertTrue(response['result'], response['error_message'])
        return response

    def assert_response_error(self, response, assert_error_code):
        self.assertEqual(response.code, 200, response.reason)
        response = json.loads(response.body)
        self.assertTrue(not response['result'] and response['error_code'] == assert_error_code,
                        response['error_message'])
